package cn.rengy.web.framework.shiro.credential;

import java.security.Principal;
import java.time.Duration;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.PasswordMatcher;
import org.apache.shiro.authc.credential.PasswordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RetryLimitPasswordMatcher extends PasswordMatcher {
	private static Logger logger = LoggerFactory.getLogger(RetryLimitPasswordMatcher.class);
	//@Autowired  
	//private StringRedisTemplate stringRedisTemplate;
	/**登录尝试次数缓存前缀*/
	private static final String LOGIN_RETRY_NUMBER="loginRetryNumber:";
	/**最大登录尝试次数*/
	private static final int MAX_FAILURE_NUMBER=5;
	public RetryLimitPasswordMatcher(PasswordService passwordService) {
		this.setPasswordService(passwordService);
	}
	@Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
//        String name=((Principal)info.getPrincipals().getPrimaryPrincipal()).getName();
//        String key=LOGIN_RETRY_NUMBER.concat(name);
//        int retryNumber=NumberUtils.toInt(stringRedisTemplate.opsForValue().get(key), 0);
//        if(retryNumber>MAX_FAILURE_NUMBER) {
//        	throw new ExcessiveAttemptsException("登录失败次数过多账户已锁定");
//        }
        boolean matches = super.doCredentialsMatch(token, info);
//        if(matches) {
//        	if(retryNumber>0) {
//        		stringRedisTemplate.delete(key);
//        	}
//        }else {
//        	//增加失败次数
//        	stringRedisTemplate.opsForValue().set(key, String.valueOf(retryNumber+1), Duration.ofHours(1));
//        }
        return matches;
    }
}
